package com.etoak.controller;

import com.etoak.bean.ResultVo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @author : 15081
 * @DATE : 2023-02-15 16:35
 **/
@RestController
@RequestMapping("/file")
@CrossOrigin
public class FileController {

    //@Value 获取配置文件中的信息

    @Value("${file.uploadPath}")
    private String uploadPath;

    @Value("${file.staticAccessPath}")
    private String staticAccessPath;


    @PostMapping("/upload")
    public ResultVo upload(MultipartFile file){
        //获取源文件名称
        //ctrl + alt + v
        String originalFilename = file.getOriginalFilename();
        // 获取文件后缀  .xxx  .png .jpg
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //生成新文件名
        String prefix = UUID.randomUUID().toString().replaceAll("-","");

        String newName = prefix + suffix;

        //上传
        try {
            file.transferTo(new File(uploadPath,newName));
        } catch (IOException e) {
            e.printStackTrace();
        }

        String  path = "http://localhost:9000"+staticAccessPath+newName;
       //返回映射地址
        return ResultVo.success().setData(path);

    }

}
